﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class MessageCenter : MonoBehaviour
{
    private static MessageCenter _instance;
    private Dictionary<string, Action<object>> _eventDictionary;

    public static MessageCenter Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<MessageCenter>();
                if (_instance == null)
                {
                    GameObject obj = new GameObject("MessageCenter");
                    _instance = obj.AddComponent<MessageCenter>();
                }
            }
            return _instance;
        }
    }

    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (_instance != this)
        {
            Destroy(gameObject);
        }
        
        _eventDictionary = new Dictionary<string, Action<object>>();
    }

    public static void Subscribe(string eventName, Action<object> listener)
    {
        if (Instance._eventDictionary.TryGetValue(eventName, out Action<object> thisEvent))
        {
            thisEvent += listener;
            Instance._eventDictionary[eventName] = thisEvent;
        }
        else
        {
            thisEvent += listener;
            Instance._eventDictionary.Add(eventName, thisEvent);
        }
    }

    public static void Unsubscribe(string eventName, Action<object> listener)
    {
        if (_instance == null) return;
        if (Instance._eventDictionary.TryGetValue(eventName, out Action<object> thisEvent))
        {
            thisEvent -= listener;
            Instance._eventDictionary[eventName] = thisEvent;
        }
    }

    public static void Publish(string eventName, object message = null)
    {
        if (Instance._eventDictionary.TryGetValue(eventName, out Action<object> thisEvent))
        {
            thisEvent?.Invoke(message);
        }
    }
}